package server;

import com.fasterxml.jackson.databind.ObjectMapper;
import config.MongoDB;
import entities.*;
import entities.Process;
import sluentities.StateMachineModelEntity;
import org.bson.types.ObjectId;
import org.mongodb.morphia.query.Query;
import java.io.*;
import java.util.*;
import sluentities.*;

/**
 * Created by sunjia on 2017/4/5.
 */
public class GrammarUpdate {

    List<Command> commands = new ArrayList<Command>();
    Map<String,Command> stringCommandMap = new HashMap<>();
    //static Set<GrammarSlotEntity> tempSlots = new HashSet<>();

    public void update (String path_Gaz, String path_Jape)throws Exception{
        DB2Jape(path_Jape);
        DB2Gazetteer(path_Gaz);
    }

    public void createJsonfromDB(String path) throws IOException {

        //写节点
        Query<NavigationEntity> q = MongoDB.instance().getDatabase().createQuery(NavigationEntity.class).field("name").equal("root");
        StateMachineModelEntity mjson = new StateMachineModelEntity();
        NavigationEntity root = q.get();
        if(root != null){
            //设置节点
            mjson.setRoot(Navi2Json(root));

            //设置commands
            for (String str : stringCommandMap.keySet()){
                Command comm = new Command();
                comm.setName(str);
                commands.add(comm);
            }
            mjson.setCommands(commands);

           //设置params
            List<Param> paramls = new ArrayList<Param>();
            Query<GrammarVariableEntity> varies = MongoDB.instance().getDatabase().createQuery(GrammarVariableEntity.class);
            for (GrammarVariableEntity vari : varies){
                String variName = vari.getName().replace("$","");
                Param param = new Param(variName, vari.getReply(), vari.getDynamicFunName(), vari.getLists(),
                        vari.getDefaultFunction(),vari.getDefaultValue(),vari.getScope());
                param.setType(vari.getType());
                param.setDefaultValue(vari.getDefaultValue());
                param.setDefaultFunction(vari.getDefaultFunction());
                paramls.add(param);

            }
            mjson.setParams(paramls);

            //设置processes
            List<ProcessEntity> processls = new ArrayList<ProcessEntity>();
            Query<ProcessEntity> processes = MongoDB.instance().getDatabase().createQuery(ProcessEntity.class);
            for (ProcessEntity p: processes){
                processls.add(p);
            }
            mjson.setProcesses(processls);

            ObjectMapper mapper = new ObjectMapper();
            String jsonString = mapper.writeValueAsString(mjson);
            OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(path,false),"UTF-8");
            fw.write(jsonString);
            //System.out.println(jsonString);
            fw.close();
        }
    }


    private StateNode Navi2Json(NavigationEntity navi) {

        StateNode naviJson = new StateNode();
        naviJson.setId(navi.getName());                          //id
        naviJson.setReply(navi.getReply());                      //reply
        naviJson.setHelpReply(navi.getHelpReply());              //helpReply
        naviJson.setQuery(navi.getQuery());                      //query
        //naviJson.setNoInput(navi.getNoInput());
        //naviJson.setInit_process(navi.getInit_process());
        List<String> tempParam = new ArrayList<>();             //param
        List<GrammarVariableEntity> tempVariLs = navi.getParams();
        for (GrammarVariableEntity tempVari : tempVariLs) {
            String variName = tempVari.getName().replace("$","");
            tempParam.add(variName);
        }
        naviJson.setParams(tempParam);                       //param
        List<StateNode> childrenJson = naviJson.getSubStateNode();
        List<NavigationEntity> children = navi.getChildren();
        for (NavigationEntity c : children) {
            childrenJson.add(Navi2Json(c));
        }
        return naviJson;
    }


    private static void resolveParamDependence(Set<String> paramNameSet){

        Set<String> paramNamenewSet = new HashSet<>();

        for (String str:paramNameSet){
            GrammarVariableEntity vari = MongoDB.instance().getDatabase().createQuery(GrammarVariableEntity.class).field("name").
                    equal(str).get();
            if(vari==null){
                System.err.println("variable "+str+" not exist!");
                continue;
            }
            for (String strparam:vari.getLists()){
                if(!paramNameSet.contains(strparam)){
                    paramNamenewSet.add(strparam);
                }
            }
        }

        if(!paramNamenewSet.isEmpty()){
            paramNameSet.addAll(paramNamenewSet);
            resolveParamDependence(paramNameSet);
        }
    }

    public static void listAll(List candidate,String prefix,int n) {
        System.out.println(prefix);

        for (int i = n; i < candidate.size(); i++) {
            String tmp = prefix+candidate.get(i);
            listAll(candidate, tmp, i + 1);
        }
    }

    private static void getAllCombination(List candicate,List preAdd,int n,List res){
        if(!preAdd.isEmpty()){
            res.add(preAdd);
        }

        for (int i = n; i < candicate.size(); i++) {
            List tmp = new ArrayList<>();
            tmp.addAll(preAdd);
            tmp.add(candicate.get(i));
            getAllCombination(candicate, tmp, i + 1,res);
        }


    }


    private static List<GrammarRuleEntity> generateVariableRules(NavigationEntity navi){

        List<GrammarRuleEntity> ret = new ArrayList<>();

        List<GrammarVariableEntity> paramList = navi.getParams();

        Set<String> paramNameSet = new HashSet<>();

        for (GrammarVariableEntity vari:paramList){
            paramNameSet.add(vari.getName());
        }

        resolveParamDependence(paramNameSet);

        List<GrammarVariableEntity> resolveParams = new ArrayList<>();

        for (String str:paramNameSet){
            GrammarVariableEntity vari = MongoDB.instance().getDatabase().createQuery(GrammarVariableEntity.class).field("name").
                    equal(str).get();
            if(vari==null){
                System.err.println("variable "+str+" not exist!");
                continue;
            }
            resolveParams.add(vari);
        }

        List<List<GrammarVariableEntity>> allCombination = new ArrayList<>();

        getAllCombination(resolveParams,new ArrayList<GrammarVariableEntity>(),0,allCombination);

        for (List<GrammarVariableEntity> combination:allCombination){

            GrammarRuleEntity rule = new GrammarRuleEntity();
            rule.setOrdered(false);
            rule.setId(new ObjectId());
            rule.setVaribleRule(true);
            List<RuleEntryEntity> ruleEntries = rule.getLists();
            for (GrammarVariableEntity vari:combination){
                RuleEntryEntity entry = new RuleEntryEntity();
                entry.setDispensable(false);
                entry.setType(1);
                entry.setName(vari.getName());
                entry.setEntry(vari.getId());
                ruleEntries.add(entry);
            }

            navi.getRules().add(rule);
            ret.add(rule);

        }
        return ret;
    }

    /*private static void generateMenuNameRule(NavigationEntity navi){

        String menuName = navi.getName();

        if(menuName.equals("root"))
            return;

        Query<GrammarSlotEntity> q = MongoDB.instance().getDatabase().createQuery(GrammarSlotEntity.class)
                .field("lists").equal(menuName);
        GrammarSlotEntity slot = q.get();
        if(slot==null){
            Query<GrammarSlotEntity> q1 = MongoDB.instance().getDatabase().createQuery(GrammarSlotEntity.class)
                    .field("name").equal(menuName);
            slot = q1.get();
            if(slot==null) {
                slot = new GrammarSlotEntity();
                slot.setId(new ObjectId());
                slot.setName(menuName);
            }
            slot.getLists().add(menuName);
            tempSlots.add(slot);
        }

        GrammarRuleEntity rule = new GrammarRuleEntity();
        rule.setOrdered(false);
        rule.setId(new ObjectId());

        RuleEntryEntity entry = new RuleEntryEntity();
        entry.setDispensable(false);
        entry.setType(0);
        entry.setName(slot.getName());
        entry.setEntry(slot.getId());

        rule.getLists().add(entry);
        navi.getRules().add(rule);

        //System.err.println(rule.getId());

    }*/


    private void DB2Jape(String path) throws IOException {

        Query<NavigationEntity> q = MongoDB.instance().getDatabase().createQuery(NavigationEntity.class);
        OutputStreamWriter fw = null;
        path = path + "/";
        try{
            File file = new File(path);
            delete(file);
            file.mkdir();
            fw = new OutputStreamWriter(new FileOutputStream(path + "main.jape", false),"UTF-8");
            fw.write("MultiPhase: TestTheGrammars\nPhases:\n");
            for(NavigationEntity navi : q){
                generateVariableRules(navi);//生成默认语法：变量全排列
                //generateMenuNameRule(navi);
                for (GrammarRuleEntity rule : navi.getRules()){
                    String strRule = "rule_" + rule.getId();
                    fw.write(strRule + "\n");
                    //System.out.println(strRule);
                    //开始写每一条Rule
                    OutputStreamWriter fwRule =
                            new OutputStreamWriter(new FileOutputStream(path + strRule + ".jape", false),"UTF-8");
                    fwRule.write("Phase: "+ strRule + "\nInput: ");
                    //Input时注意判断语义槽还是变量,并用List存放变量
                    List<RuleEntryEntity> entries = rule.getLists();
                    List<RuleEntryEntity> entries_vari = new ArrayList<RuleEntryEntity>();
                    for(RuleEntryEntity entry : entries){
                        String entryName = entry.getName();
                        if (entry.getType() == 1){
                            entries_vari.add(entry);//用于之后的循环
                            GrammarVariableEntity vari = MongoDB.instance().getDatabase().createQuery(GrammarVariableEntity.class).field("name").
                                    equal(entryName).get();
                            System.out.println(vari.getName());
                            if (vari.getType().contains(".")) {
                                entryName = vari.getType().split("\\.")[0];
                            }else {
                                entryName = vari.getType();
                            }
                        }
                        fwRule.write("\"" + entryName + "\"" + " ");
                    }
                    fwRule.write("\nOptions: control = brill debug = true\n");
                    fwRule.write("\nRule: " + strRule + "\n(\n");
                    fwRule.write(makeEntry_All(rule.getLists(),rule.getOrdered()) + "\n");
                    fwRule.write(")\n:" + strRule + "\n-->\n" + "{\n");
                    Formatter fmt = new Formatter();
                    fmt.format("\tAnnotationSet as= (gate.AnnotationSet)bindings.get(\"%s\");\n"
                                    +"\tFeatureMap features=Factory.newFeatureMap();\n"
                                    +"\tdouble effectiveLength=0;\n"
                                    +"\tint distance=0;\n"
                                    +"\tfor(Annotation i : as){\n"
                                    +"\t\tString matchedString=doc.getContent().toString().substring(\n"
                                    +"\t\t\ti.getStartNode().getOffset().intValue(), i.getEndNode().getOffset().intValue());\n"
                                    +"\t\tfeatures.put(\"MatchedToken:\"+matchedString, i.getFeatures().get(\"matchedString\")+\":\"+i.getType());\n"
                                    +"\t\tlong matchedLength=(long)matchedString.length();\n"
                                    +"\t\tdistance+=(int)i.getFeatures().get(\"distance\");\n"
                                    +"\t\teffectiveLength+=(double)matchedLength;\n\t}\n\n"
                                    +"\tFeatureMap featuresSlots=Factory.newFeatureMap();\n\n",
                            strRule);
                    //一条语法有几个变量要循环几次
                    for (RuleEntryEntity entry : entries_vari){
                        String variName = "vari_" + entry.getEntry().toString();
                        fmt.format("\tAnnotationSet as_%s= (gate.AnnotationSet)bindings.get(\"%s\");\n"
                                        +"\tif(as_%s != null && as_%s.size() != 0){\n"
                                        +"\t\tFeatureMap featuresGet = as_%s.iterator().next().getFeatures();\n"
                                        +"\t\tfeaturesSlots.put(\"%s\", featuresGet);\n\t}\n\n",
                                variName, variName, variName, variName, variName, entry.getName());
                    }
                    fmt.format("\tfeatures.put(\"effective_length\", effectiveLength-distance);\n"
                                    +"\tfeatures.put(\"rule\", \"%s\");\n"
                                    +"\tfeatures.put(\"type\", \"stateNode\");\n"
                                    +"\tfeatures.put(\"slotNum\", as.size());\n"
                                    +"\tfeatures.put(\"slots\", featuresSlots);\n",
                            navi.getName());
                    if(rule.isVaribleRule()){
                        fmt.format("\tdouble inputLen = (double)doc.getContent().toString().length();\n"
                                        +"\tif(inputLen*0.4<effectiveLength)\n"
                                        +"\t\toutputAS.add(as.firstNode(), as.lastNode(), \"command\", features);\n}\n\n");
                    }else {
                        fmt.format("\toutputAS.add(as.firstNode(), as.lastNode(), \"command\", features);\n}\n\n");
                    }
                    fwRule.write(fmt.toString());
                    fwRule.close();
                }
            }
            //command
            Query<Command> q_command = MongoDB.instance().getDatabase().createQuery(Command.class);
            for(Command command : q_command){
                stringCommandMap.put(command.getName(), command);
                for (GrammarRuleEntity rule : command.getRules()){
                    String strCommand = "command_" + rule.getId();
                    fw.write(strCommand + "\n");
                    OutputStreamWriter fwCommand =
                            new OutputStreamWriter(new FileOutputStream(path + strCommand + ".jape", false),"UTF-8");
                    fwCommand.write("Phase: "+ strCommand + "\nInput: ");
                    Set<String> entrySet2 = new HashSet<String>();
                    List<RuleEntryEntity> entries2 = rule.getLists();
                    for(RuleEntryEntity entry : entries2){
                        String entryName = entry.getName();
                        entrySet2.add(entryName);
                    }
                    for(String name : entrySet2){
                        fwCommand.write("\"" + name + "\"" + " ");
                    }
                    fwCommand.write("\nOptions: control = brill debug = true\n");
                    fwCommand.write("\nRule: " + strCommand + "\n(\n");
                    fwCommand.write(makeEntry_All(rule.getLists(),command.getOrdered()) + "\n");
                    fwCommand.write(")\n:" + strCommand + "\n-->\n" + "{\n");
                    Formatter fmt = new Formatter();
                    fmt.format("\tAnnotationSet as= (gate.AnnotationSet)bindings.get(\"%s\");\n"
                                    +"\tFeatureMap features=Factory.newFeatureMap();\n"
                                    +"\tdouble effectiveLength=0;\n"
                                    +"\tint distance=0;\n"
                                    +"\tfor(Annotation i : as){\n"
                                    +"\t\tString matchedString=doc.getContent().toString().substring(\n"
                                    +"\t\t\ti.getStartNode().getOffset().intValue(), i.getEndNode().getOffset().intValue());\n"
                                    +"\t\tfeatures.put(\"MatchedToken:\"+matchedString, i.getFeatures().get(\"matchedString\")+\":\"+i.getType());\n"
                                    +"\t\tlong matchedLength=(long)matchedString.length();\n"
                                    +"\t\tdistance+=(int)i.getFeatures().get(\"distance\");\n"
                                    +"\t\teffectiveLength+=(double)matchedLength;\n\t}\n\n"
                                    +"\tFeatureMap featuresSlots=Factory.newFeatureMap();\n\n"
                                    +"\tfeatures.put(\"effective_length\", effectiveLength-distance);\n"
                                    +"\tfeatures.put(\"rule\", \"%s\");\n"
                                    +"\tfeatures.put(\"type\", \"command\");\n"
                                    +"\tfeatures.put(\"slotNum\", as.size());\n"
                                    +"\tfeatures.put(\"slots\", featuresSlots);\n"
                                    +"\toutputAS.add(as.firstNode(), as.lastNode(), \"command\", features);\n}\n\n",
                            strCommand,command.getName());
                    fwCommand.write(fmt.toString());
                    fwCommand.close();

                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                fw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static String makeEntry_All(List<RuleEntryEntity> entries, boolean order){

        String str = "";
        String strdis = "";//可选
        Map<String, String> entriesAllMap= new LinkedHashMap<>();//用于有序语法
        Map<String, String> varOrderMap=new HashMap<>();//用于存储同一类型的变量
        Set<ObjectId> quchongVOM=new HashSet<>();
        List<String> entriesdis = new ArrayList<String>();
        List<String> entriesindis = new ArrayList<String>();//必选

        for (RuleEntryEntity entry : entries){
            String entryName = entry.getName();
            String line = "";
            if (entry.getType() == 1) {//变量
                GrammarVariableEntity vari = MongoDB.instance().getDatabase().createQuery(GrammarVariableEntity.class).field("name").
                        equal(entryName).get();
                //判断下type的格式是否正确，不正确直接跳出。
                String variType = vari.getType();
                if (variType.contains(".") && variType.contains("==")) {
                    String variTypeFormate = "\"" + variType.split("\\.")[0] + "\"" + ".\""
                            + variType.split("\\.")[1].split("==")[0] + "\"==\""
                            + variType.split("\\.")[1].split("==")[1] + "\"";
                    line = "({" +  variTypeFormate + "})" + ":" + "vari_" + entry.getEntry() + " ";
                } else {
                    line = "({\"" +  variType + "\"})" + ":" + "vari_" + entry.getEntry() + " ";
                }
                if (entry.isDispensable()){ //可选的格式在下面处理
                    entriesdis.add(line);
                    entriesAllMap.put(line, "dis");
                }else {
                    entriesindis.add(line);
                    entriesAllMap.put(line, "indis");//必选
                    if(!quchongVOM.contains(entry.getEntry())){
                        if(varOrderMap.containsKey(variType)){
                            String temp=varOrderMap.get(variType);
                            temp=temp+"#"+line;
                            varOrderMap.put(variType,temp);
                        }else {
                            varOrderMap.put(variType,line);
                        }
                        quchongVOM.add(entry.getEntry());
                    }
                }
            }else {//语义槽
                line = "{\"" + entryName +"\"}";
                if (entry.isDispensable()) { //可选的格式在下面处理
                    entriesdis.add(line);
                    entriesAllMap.put(line, "dis");
                } else {//必选
                    entriesindis.add("(" + line + ") ");
                    entriesAllMap.put("(" + line + ") ", "indis");
                }
            }
        }
        //去重
        entriesdis=filterSLots(entriesdis);
        entriesindis=filterSLots(entriesindis);

        if(entriesdis.size()>0){//可选的entry大于0
            strdis = "(" + JoinStr(entriesdis," | ") + ")* ";
        }
        List<String> res = new ArrayList<String>();
        if (order) {//有序，只需要罗列出res就行
            str = getOrderRule(entriesAllMap);
        }else{
            allRange(entriesindis, 0, entriesindis.size()-1, res, strdis,varOrderMap);
            str = JoinStr(res, "|\n");
        }
        return str;
    }

    private static String getOrderRule(Map<String, String> entriesAllMap){

        String str = "";
        for(Map.Entry<String, String> entry : entriesAllMap.entrySet() ){
            String line = entry.getKey();
            String isdis = entry.getValue();
            if (isdis.equals("dis")){//可选
                line = "(" + entry.getKey() + ")* ";
            }
            str += line;
        }
        return str;
    }

    private static List<String> filterSLots(List<String> slots){
        Set<String> slotSet = new HashSet<String>();
        for (String str:slots){
            slotSet.add(str);
        }
        List<String> newSet = new ArrayList<String>();
        for (String str:slotSet){
            newSet.add(str);
        }
        return newSet;
    }

    private static String JoinStr(List<String> strlist, String sep){
        String str = "";
        for (String string : strlist){
            str += string;
            str += sep;
        }
        if(strlist.size()>0){
            str = str.substring(0, str.length()-sep.length());
        }
        return str;
    }
    private static boolean containAndOrdered(List<String> l1,List<String> l2){
        boolean res=false;
        int p1=0,p2=0;
        while (p1<l1.size()&&p2<l2.size()){
            if(l1.get(p1).equals(l2.get(p2))){
                p2++;
            }
            p1++;
        }
        if(p2==l2.size())res=true;
        return res;
    }
    //获取所有排列组合
    private static void allRange(List<String> entries, int n, int m, List<String> res, String str2,Map<String,String> varOrderMap){
        if(n==m){
            boolean flag=true;
            if(varOrderMap.size()>0){
                for (Map.Entry<String, String> entry : varOrderMap.entrySet()) {
                    if(!flag)break;
                    String temp=entry.getValue();
                    if(temp.contains("#")){
                        String[] order=temp.split("#");
                        List<String> temlist=new ArrayList<>();
                        for(int i=0;i<order.length;i++)temlist.add(order[i]);
                        flag=containAndOrdered(entries,temlist);
                    }
                }
            }
            if(flag)res.add("\t(" + str2 + JoinStr(entries,str2) + str2 + ")");
        } else {
            for (int i=n;i<=m;i++){
                String tmp = entries.get(n);
                entries.set(n, entries.get(i));
                entries.set(i, tmp);
                allRange(entries, n+1, m, res, str2,varOrderMap);
                tmp = entries.get(n);
                entries.set(n, entries.get(i));
                entries.set(i, tmp);
            }
        }
    }

    private static void delete(File file) throws IOException {
        try{
            if (file.isDirectory()) {
                if (file.list().length == 0) {
                    file.delete();
                }else {
                    String files[] = file.list();
                    for (String temp : files) {
                        File fileDelete = new File(file, temp);
                        delete(fileDelete);
                    }
                    if (file.list().length == 0) {
                        file.delete();
                    }
                }
            } else {
                file.delete();
            }
        }catch(IOException e){return;}
    }

    private static void DB2Gazetteer(String path) throws IOException {

        Query<GrammarSlotEntity> q_s = MongoDB.instance().getDatabase().createQuery(GrammarSlotEntity.class);
        Query<GrammarElementEntity> q_e = MongoDB.instance().getDatabase().createQuery(GrammarElementEntity.class);//语义要素
        List<GrammarSlotEntity> list_s = q_s.asList();
        //list_s.addAll(tempSlots);
        OutputStreamWriter fw = null;
        path = path + "/";
        try{
            File file = new File(path);
            delete(file);
            file.mkdir();
            fw =new OutputStreamWriter(new FileOutputStream(path + "list.def",false),"UTF-8");
            for(GrammarSlotEntity slot : list_s){
                if(!slot.getLists().isEmpty()){
                    String slotName = slot.getName();
                    fw.write(slotName + ".lst::::" + slotName + "\n");
                    OutputStreamWriter fwSlot =
                            new OutputStreamWriter(new FileOutputStream(path + slotName + ".lst", false),"UTF-8");
                    for (String entry : slot.getLists()){
                        fwSlot.write(entry+"\n");
                    }
                    fwSlot.close();
                }
            }
            for(GrammarElementEntity element : q_e){
                if (element != null) {
                    String eleName = element.getName();
                    fw.write(eleName + ".lst::::" + eleName + "\n");
                    OutputStreamWriter fwEle =
                            new OutputStreamWriter(new FileOutputStream(path + eleName + ".lst", false), "UTF-8");
                    List<EmbedElementEntity> embedLs = element.getElelists();
                    for (EmbedElementEntity embed : embedLs) {
                        List<String> userInputLs = embed.getUserinput();
                        String standardName = embed.getStandardName();
                        Map<String, String> attMap = embed.getAttlists();
                        String attString = "";
                        if (attMap != null ) {
                            for (Map.Entry<String, String> entry : attMap.entrySet()) {
                                String pair = entry.getKey() + "=" + entry.getValue();
                                attString += pair + "&";
                            }
                            for (String userInput : userInputLs) {
                                String line = userInput + "&" + "抽取名=" + standardName + "&" + attString.substring(0, attString.length() - 1);
                                fwEle.write(line + "\n");
                            }
                        } else {
                            for (String userInput : userInputLs) {
                                String line = userInput + "&" + "抽取名=" + standardName;
                                fwEle.write(line + "\n");
                            }
                        }
                    }
                    fwEle.close();
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                fw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static void updateGram(){

        MongoDB.setDBConf("nxyd", "localhost", "", "", 27017);

        GrammarUpdate grammarUpdate = new GrammarUpdate();
        try {
            try {
                String path_Gaz = GrammarUpdate.class.getClassLoader().
                        getResource("plugins/gazetteer/").getPath();
                String path_Jape = GrammarUpdate.class.getClassLoader().
                        getResource("plugins/jape/").getPath();
                System.out.println(path_Gaz);
                grammarUpdate.update(path_Gaz, path_Jape);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("更新失败，内部IO错误");
                return;
            }
            String path_Json = GrammarUpdate.class.getClassLoader().
                    getResource("plugins/nodeInfo.json").getPath();
//            grammarUpdate.createJsonfromDB(path_Json);
            System.out.println("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("更新失败，内部系统错误");
        }
    }

    private static void testSlot(){

        MongoDB.setDBConf("hzrs", "localhost", "", "", 27017);
        Query<GrammarSlotEntity> q = MongoDB.instance().getDatabase().createQuery(GrammarSlotEntity.class)
                .field("lists").equal("麻烦问一下");
        for (GrammarSlotEntity slot:q){
            System.out.println(slot.getName());

        }
    }

    public static void main(String[] args) {
        updateGram();
    }
}
